package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.dto.goods.TextConvertGoodsDto;
import com.uzai.common.dto.pyq.*;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.RegularUtil;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.BeanMapUtil;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.EmojiUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.feign.turnlink.TbPartnerurlAnalysisDto;
import com.uzai.console.dto.feign.turnlink.TbPwdAnalysisDto;
import com.uzai.console.dto.pyq.pyqjobdetail.PyqJobDetailIdDto;
import com.uzai.console.dto.pyq.pyqmaterial.TurnlinkDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.PyqJobDetail;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.ClientApiService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.feign.dto.ConvertGoodsDto;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.pyq.PyqFollowSendService;
import com.uzai.console.service.pyq.PyqJobDetailService;
import com.uzai.console.service.pyq.PyqMaterialService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.feign.turnlink.TbPartnerurlAnalysisVo;
import com.uzai.console.vo.feign.turnlink.TbPwdAnalysisVo;
import com.uzai.console.vo.pyq.pyqjobdetail.PyqJobDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 朋友圈跟发发送
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqFollowSendServiceImpl implements PyqFollowSendService {

    Logger logger = LoggerFactory.getLogger(PyqFollowSendServiceImpl.class);

    @Autowired
    private PyqFollowConfigMapper pyqFollowConfigMapper;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private PyqFollowSendMapper pyqFollowSendMapper;
    @Autowired
    private PyqFollowedContentMapper pyqFollowedContentMapper;
    @Autowired
    private PyqFollowContentMapper pyqFollowContentMapper;
    @Autowired
    private PyqFollowedCommentMapper pyqFollowedCommentMapper;
    @Autowired
    private PyqFollowCommentMapper pyqFollowCommentMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private PyqJobMapper pyqJobMapper;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private PyqMaterialService pyqMaterialService;
    @Autowired
    private PyqAutoSendMapper pyqAutoSendMapper;
    @Autowired
    private ClientApiService clientApiService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;

    /**
     * 跟发朋友圈发送
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void followSendPyq(PyqFollowSendDto pyqFollowSendDto, PyqFollowConfig pyqFollowConfig){

        if(pyqFollowConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "跟发配置不存在");
        }

        if(pyqFollowConfig.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqFollowConfig.getDevicePlanId(), pyqFollowConfig.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqDevicePlan.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        //循环机器人，查询机器人发送记录
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            int totalCount = 0;
            Long pyqJobId = IdWorker.getId();
            int now = DateUtil.getNowTime();
            for(Long deviceUniqueId : deviceUniqueIdList){
                //查询该机器人是否发送过该朋友圈id
                PyqFollowSend pyqFollowSend = pyqFollowSendMapper.selectByDeviceUniqueIdAndSnsId(deviceUniqueId, pyqFollowSendDto.getSnsId());
                //不为空，表示已经发送该朋友圈，则跳过
                if(pyqFollowSend != null){
                    continue;
                }

                //发送明细
                Boolean result = sendPyqJobDetail(pyqFollowConfig, deviceUniqueId, pyqJobId, pyqFollowSendDto, now);
                if(result){
                    totalCount ++ ;
                }
            }

            //大于0，才有主表
            if(totalCount > 0){
                PyqJob pyqJob = new PyqJob();
                pyqJob.setId(pyqJobId);
                pyqJob.setMerId(pyqFollowConfig.getMerId());
                pyqJob.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
                pyqJob.setType(1);//图文
                pyqJob.setSource(2); //自动跟发
                pyqJob.setPlatform(0);
                pyqJob.setDevicePlanId(pyqFollowConfig.getDevicePlanId());
                pyqJob.setCreateTime(now);
                pyqJob.setUpdateTime(now);
                pyqJob.setSendTime(now);
                pyqJob.setImgs(Tools.getStrEmpty(JSONObject.toJSONString(pyqFollowSendDto.getImgList())));
                pyqJob.setContent(pyqFollowSendDto.getContent());
                pyqJob.setCommentContent(Tools.getStrEmpty(JSONObject.toJSONString(pyqFollowSendDto.getCommentContentList())));
                pyqJob.setTotalCount(totalCount);

                //添加发送任务
                pyqJobMapper.insert(pyqJob);
            }
        }
    }

    /**
     * 跟发朋友圈发送内容
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void followSendPyqContent(PyqInfoDto pyqInfoDto, PyqFollowConfig pyqFollowConfig){

        if(pyqFollowConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "跟发配置不存在");
        }

        if(pyqFollowConfig.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqFollowConfig.getDevicePlanId(), pyqFollowConfig.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqDevicePlan.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        //循环机器人，查询机器人发送记录
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            int totalCount = 0;
            Long pyqJobId = IdWorker.getId();
            int now = DateUtil.getNowTime() + 10; //延迟10秒跟发
            for(Long deviceUniqueId : deviceUniqueIdList){
                //查询该机器人是否发送过该朋友圈id
                PyqFollowContent pyqFollowContent = pyqFollowContentMapper.selectByDeviceUniqueIdAndFollowedSnsId(deviceUniqueId, pyqInfoDto.getSnsId());
                //不为空，表示已经发送该朋友圈，则跳过
                if(pyqFollowContent != null){
                    continue;
                }
                //发送明细
                Boolean result = sendContentPyqJobDetail(pyqFollowConfig, deviceUniqueId, pyqJobId, pyqInfoDto, now);
                if(result){
                    totalCount ++ ;
                }
            }

            //大于0，才有主表
            if(totalCount > 0){
                PyqJob pyqJob = new PyqJob();
                pyqJob.setId(pyqJobId);
                pyqJob.setMerId(pyqFollowConfig.getMerId());
                pyqJob.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
                pyqJob.setType(1);//图文
                pyqJob.setSource(2); //自动跟发
                pyqJob.setPlatform(0);
                pyqJob.setDevicePlanId(pyqFollowConfig.getDevicePlanId());
                pyqJob.setCreateTime(now);
                pyqJob.setUpdateTime(now);
                pyqJob.setSendTime(now+5); //延迟5秒发送
                pyqJob.setContent(pyqInfoDto.getContent());
                pyqJob.setCommentContent(null);
                pyqJob.setTotalCount(totalCount);
                //新版协议imgs字段作废
                pyqJob.setImgs(null);
                //媒体信息
                pyqJob.setFeedMedia(Tools.getStrEmpty(JSONObject.toJSONString(pyqInfoDto.getMediaList())));
                //视频号信息
                pyqJob.setVideoNumber(Tools.getStrNull(JSONObject.toJSONString(pyqInfoDto.getPyqVideoNumberDto())));
                //朋友圈附件类型(0-链接；2-图片;3-短视频;4-长视频;5-视频号)
                pyqJob.setAttachType(pyqInfoDto.getAttachType());

                //添加发送任务
                pyqJobMapper.insert(pyqJob);
            }
        }
    }

    /**
     * 跟发朋友圈功能发送评论
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void followSendPyqComment(PyqCommentDto pyqCommentDto, PyqFollowConfig pyqFollowConfig){
        if(pyqFollowConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "跟发配置不存在");
        }

        if(pyqFollowConfig.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqFollowConfig.getDevicePlanId(), pyqFollowConfig.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //评论列表
        List<PyqComment> commentList = pyqCommentDto.getList();
        if(commentList == null || commentList.size() ==0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "评论为空");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqDevicePlan.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        //循环机器人，查询机器人发送记录
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            int totalCount = 0;
            Long pyqJobId = IdWorker.getId();
            int now = DateUtil.getNowTime();
            for(Long deviceUniqueId : deviceUniqueIdList){
                for(PyqComment pyqComment : commentList){
                    //循环评论列表，插入查询数据库
                    PyqFollowComment pyqFollowComment = pyqFollowCommentMapper.selectByDeviceUniqueIdAndFollowedSnsIdAndFollowedCommentId(deviceUniqueId, pyqComment.getSnsId(), pyqComment.getCommentId());
                    //不为空，表示已经发送该朋友圈评论，则跳过
                    if(pyqFollowComment == null){ //为空，表示新的评论，插入数据库
                        sendCommentPyqJobDetail(pyqFollowConfig, deviceUniqueId, pyqJobId, pyqComment, now);
                    }
                }
            }
        }
    }

    /**
     * 跟发发送朋友圈商品明细
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param pyqFollowConfig
     * @return null
     */
    public boolean sendPyqJobDetail(PyqFollowConfig pyqFollowConfig, Long deviceUniqueId, Long pyqJobId , PyqFollowSendDto pyqFollowSendDto, Integer now){

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, null, pyqFollowConfig.getMerId());
        if(device == null){
            return false;
        }

        //赋值子任务明细
        PyqJobDetail pyqJobDetail = new PyqJobDetail() ;
        pyqJobDetail.setId(String.valueOf(IdWorker.getId()));
        pyqJobDetail.setVersion(0L);
        pyqJobDetail.setMerId(pyqFollowConfig.getMerId());
        pyqJobDetail.setJobId(pyqJobId);
        pyqJobDetail.setStatus(PyqJobDetailStatusEnum.NOSEND.getValue());
        pyqJobDetail.setDeviceUniqueId(deviceUniqueId);
        pyqJobDetail.setDeviceType(device.getRecvmsgType());
        pyqJobDetail.setType(1);
        pyqJobDetail.setPlatform(0);//淘宝
        pyqJobDetail.setSource(2);//发送来源（0手动发送；1自动发圈；2自动跟发）
        pyqJobDetail.setStartTime(now);
        pyqJobDetail.setSendTime(now);
        //添加商品图片
        pyqJobDetail.setImgs(Tools.getStrEmpty(JSONObject.toJSONString(pyqFollowSendDto.getImgList())));

        //2023-08-08 修改增加媒体信息
        if(pyqFollowSendDto.getImgList() != null && pyqFollowSendDto.getImgList().size() > 0){
            List<FeedMedia> feedMediaList = new ArrayList<>();
            for (String img : pyqFollowSendDto.getImgList()) {
                FeedMedia feedMedia = new FeedMedia();
                feedMedia.setUrl(img);
                feedMediaList.add(feedMedia);
            }
            pyqJobDetail.setFeedMediaList(Tools.getStrEmpty(JSONObject.toJSONString(feedMediaList)));
        }

        pyqJobDetail.setCreateTime(now);
        pyqJobDetail.setUpdateTime(now);
        //朋友圈内容
        String content = Tools.getStr(pyqFollowSendDto.getContent());
        //判断是否替换淘口令和短链接
        if(Tools.getInteger(pyqFollowConfig.getTurnlink()).intValue() == 1){ //--开启替换
            if(StringUtils.isNotBlank(content)){
                //短链接替换
                //先解析第三方工具商的短链接
                String shortUrl_old = Tools.getStrEmpty(Tools.findHttpUrlByRegex(content));
                if(StringUtils.isNotBlank(shortUrl_old)){//不等于空，则调用解析第三方工具商短链接接口
                    TbPartnerurlAnalysisVo tbPartnerurlAnalysisVo = tbPartnerurlAnalysis(shortUrl_old, device);
                    if(tbPartnerurlAnalysisVo != null){
                        //商品id
                        String itemId = Tools.getStr(tbPartnerurlAnalysisVo.getItemId());
                        String bizSceneId = tbPartnerurlAnalysisVo.getBizSceneId();
                        if(StringUtils.isNotBlank(itemId)){ //商品id不为空，根据商品id进行转链
                            //通过商品id进行转链
                            SimpleTurnlinkVo content_simpleTurnlinkVo = turnlinkSimple(null, null, shortUrl_old, device, bizSceneId, pyqFollowConfig.getDevicePlanId(), 0);
                            if(content_simpleTurnlinkVo != null){
                                //新的短链接
                                String content_buyUrl_new = Tools.getStr(content_simpleTurnlinkVo.getBuyUrl());
                                content = content.replace(shortUrl_old, content_buyUrl_new);
                            }
                        }
                    }
                }

                //淘口令替换
                String content_purePwd_old  = Tools.getStr(Tools.findTbPwdByRegex(content));
                if(StringUtils.isNotBlank(content_purePwd_old)){
                    SimpleTurnlinkVo content_simpleTurnlinkVo = turnlinkSimple(null, content_purePwd_old, null, device, null, pyqFollowConfig.getDevicePlanId(), 0);
                    if(content_simpleTurnlinkVo != null){
                        //新的淘口令
                        String content_purePwd_new = Tools.getStr(content_simpleTurnlinkVo.getPurePwd());
                        if(StringUtils.isBlank(content_purePwd_new)){
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                    pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                    "",0L,
                                    "未获取到淘口令")));
                            return false;
                        }
                        content = content.replace(content_purePwd_old, content_purePwd_new);
                    }
                }
            }
        }
        pyqJobDetail.setContent(content);

        //评论内容替换变量
        String commentContent = "";
        List<String> commentContentList = pyqFollowSendDto.getCommentContentList();
        if(commentContentList != null && commentContentList.size() > 0) {
            commentContentList.removeIf(s -> StringUtils.isBlank(s));
            commentContent = JSONObject.toJSONString(commentContentList);
        }
        if(Tools.getInteger(pyqFollowConfig.getTurnlink()).intValue() == 1) { //--开启替换
            if(StringUtils.isNotBlank(commentContent)){
                //替换短链接
                //先解析第三方工具商的短链接
                String shortUrl_old = Tools.getStrEmpty(Tools.findHttpUrlByRegex(commentContent));
                if(StringUtils.isNotBlank(shortUrl_old)){//不等于空，则调用解析第三方工具商短链接接口
                    TbPartnerurlAnalysisVo tbPartnerurlAnalysisVo = tbPartnerurlAnalysis(shortUrl_old, device);
                    if(tbPartnerurlAnalysisVo != null){
                        //第三方工具商的短链接对应的长链接
                        String itemId = Tools.getStr(tbPartnerurlAnalysisVo.getItemId());
                        //业务场景ID
                        String bizSceneId = tbPartnerurlAnalysisVo.getBizSceneId();
                        if(StringUtils.isNotBlank(itemId)){
                            //通过商品id进行转链
                            SimpleTurnlinkVo commentContent_simpleTurnlinkVo = turnlinkSimple(itemId, null, null, device, bizSceneId, pyqFollowConfig.getDevicePlanId(), 0);
                            if(commentContent_simpleTurnlinkVo != null){
                                //新的短链接
                                String commentContent_buyUrl_new = Tools.getStr(commentContent_simpleTurnlinkVo.getBuyUrl());
                                if(StringUtils.isBlank(commentContent_buyUrl_new)){
                                    return false;
                                }
                                commentContent = commentContent.replace(shortUrl_old, commentContent_buyUrl_new);
                            }
                        }
                    }
                }

                //替换淘口令
                String commentContent_purePwd_old  = Tools.getStr(Tools.findTbPwdByRegex(commentContent));
                if(StringUtils.isNotBlank(commentContent_purePwd_old)){
                    SimpleTurnlinkVo commentContent_simpleTurnlinkVo = turnlinkSimple(null, commentContent_purePwd_old,null, device, null, pyqFollowConfig.getDevicePlanId(), 0);
                    if(commentContent_simpleTurnlinkVo != null){
                        //新的淘口令
                        String commentContent_purePwd_new = Tools.getStr(commentContent_simpleTurnlinkVo.getPurePwd());
                        if(StringUtils.isBlank(commentContent_purePwd_new)){
                            return false;
                        }
                        commentContent = commentContent.replace(commentContent_purePwd_old, commentContent_purePwd_new);
                    }
                }
            }
        }
        pyqJobDetail.setCommentContent(commentContent);

        //关键词过滤
        String ignore = pyqFollowConfig.getIgnore();
        if(StringUtils.isNotBlank(ignore)){
            try {
                List<String> ignoreList = JSONObject.parseArray(ignore, String.class);
                if(ignoreList != null && ignoreList.size() > 0){
                    for (String ignoreKey : ignoreList){
                        if(content.contains(ignoreKey)){
                            return false;
                        }
                        if(commentContent.contains(ignoreKey)){
                            return false;
                        }
                    }
                }
            }catch (Exception e){

            }
        }

        //是否开启插入随机表情
        Integer emoji = Tools.getInteger(pyqFollowConfig.getEmoji());
        if(emoji == 1){ //开启插入随机表情
            //朋友圈内容前后各插2个
            //content = EmojiUtil.getRandomEmoji() + EmojiUtil.getRandomEmoji() + content + EmojiUtil.getRandomEmoji() + EmojiUtil.getRandomEmoji();
            content = content + EmojiUtil.getRandomEmoji() + EmojiUtil.getRandomEmoji();
            pyqJobDetail.setContent(content);
            //评论前后各插一个
//            List<String> commentContentList_emoji = JSONObject.parseArray(commentContent, String.class);
//            if(commentContentList_emoji != null && commentContentList_emoji.size() > 0) {
//                //List<String> list1 = commentContentList_emoji.stream().map(s -> EmojiUtil.getRandomEmoji() + s + EmojiUtil.getRandomEmoji()).collect(Collectors.toList());
//                List<String> list1 = commentContentList_emoji.stream().map(s -> s + EmojiUtil.getRandomEmoji()).collect(Collectors.toList());
//                commentContent = JSONObject.toJSONString(list1);
//                pyqJobDetail.setCommentContent(commentContent);
//            }
        }

        List<PyqJobDetail> pyqJobDetailList = new ArrayList<>();
        pyqJobDetailList.add(pyqJobDetail);

        try{
            int time1 = DateUtil.getNowTime();

            // UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.pyqMsgPush(pyqJobDetailList);
            //elasticsearchUtil.addData(JSONObject.parseObject(JSONObject.toJSONString(pyqJobDetail)), EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetail.getId());
            String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetail.getMerId());
            //保存发送消息
            List<Map<String, Object>> list = BeanMapUtil.objectList2ListMap(pyqJobDetailList);
            boolean result = elasticsearchUtilGroupMsg.addDataBatch(list, uzai_pyq_job_detail);

            int time2 = DateUtil.getNowTime();
            logger.info("跟发朋友圈功能，调用微服务发送明细完成---usetime={}, 机器人唯一id={}, result={}", time2-time1, pyqJobDetail.getDeviceUniqueId(), JSONObject.toJSONString(result));
            if(result){ //成功发送
                //插入自动发送记录表中
                PyqFollowSend pyqFollowSend = new PyqFollowSend();
                pyqFollowSend.setId(IdWorker.getId());
                pyqFollowSend.setMerId(pyqFollowConfig.getMerId());
                pyqFollowSend.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                pyqFollowSend.setDeviceUniqueId(deviceUniqueId);
                pyqFollowSend.setSendTime(now);
                pyqFollowSend.setSnsId(pyqFollowSendDto.getSnsId());
                pyqFollowSend.setReleaseTime(pyqFollowSendDto.getReleaseTime());
                pyqFollowSend.setReleaseWxid(pyqFollowSendDto.getReleaseWxid());
                pyqFollowSend.setCreateTime(now);
                pyqFollowSend.setUpdateTime(now);
                //添加到记录表中
                pyqFollowSendMapper.insertSelective(pyqFollowSend);
            }
        }catch (Exception e){
            logger.error("跟发朋友圈，出错，eror={}",e.getMessage());
            return false;
        }

        return true;

    }

    /**
     * 跟发朋友圈发送内容
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param pyqFollowConfig
     * @return null
     */
    public boolean sendContentPyqJobDetail(PyqFollowConfig pyqFollowConfig, Long deviceUniqueId, Long pyqJobId , PyqInfoDto pyqInfoDto, Integer now){

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, null, pyqFollowConfig.getMerId());
        if(device == null){
            return false;
        }

        //赋值子任务明细
        PyqJobDetail pyqJobDetail = new PyqJobDetail() ;
        pyqJobDetail.setId(String.valueOf(IdWorker.getId()));
        pyqJobDetail.setVersion(0L);
        pyqJobDetail.setMerId(pyqFollowConfig.getMerId());
        pyqJobDetail.setJobId(pyqJobId);
        pyqJobDetail.setStatus(PyqJobDetailStatusEnum.NOSEND.getValue());
        pyqJobDetail.setDeviceUniqueId(deviceUniqueId);
        pyqJobDetail.setDeviceType(device.getRecvmsgType());
        pyqJobDetail.setType(1);
        pyqJobDetail.setPlatform(0);//淘宝
        pyqJobDetail.setSource(2);//发送来源（0手动发送；1自动发圈；2自动跟发）
        pyqJobDetail.setStartTime(now);
        pyqJobDetail.setSendTime(now);

        //新版协议imags作废
        pyqJobDetail.setImgs(null);
        //媒体信息
        pyqJobDetail.setFeedMediaList(Tools.getStrEmpty(JSONObject.toJSONString(pyqInfoDto.getMediaList())));
        //视频号信息
        pyqJobDetail.setPyqVideoNumber(Tools.getStrNull(JSONObject.toJSONString(pyqInfoDto.getPyqVideoNumberDto())));
        //朋友圈附件类型(0-链接；2-图片;3-短视频;4-长视频;5-视频号)
        pyqJobDetail.setAttachType(pyqInfoDto.getAttachType());
        pyqJobDetail.setCreateTime(now);
        pyqJobDetail.setUpdateTime(now);
        //朋友圈内容
        String content = Tools.getStr(pyqInfoDto.getContent());
        //商品信息
        String itemId = null;
        String itemName = null;

        //判断是否替换淘口令和短链接
        if(Tools.getInteger(pyqFollowConfig.getTurnlink()).intValue() == 1){ //--开启替换
            if(StringUtils.isNotBlank(content)){
                //短链接替换
                //先解析第三方工具商的短链接
                List<String> shortUrlList_old = Tools.findHttpUrlListByRegex(content);
                if(shortUrlList_old != null && shortUrlList_old.size() > 0){
                    for (String shortUrl_old :shortUrlList_old){
                        if(StringUtils.isNotBlank(shortUrl_old)) {
                            TextConvertGoodsDto textConvertGoodsDto = new TextConvertGoodsDto();
                            textConvertGoodsDto.setMerId(pyqFollowConfig.getMerId());
                            textConvertGoodsDto.setText(shortUrl_old);
                            UzaiRespVo<ConvertGoodsDto> analyzeRes = clientApiService.convertGoods(textConvertGoodsDto);
                            if (analyzeRes.getCode() != 200) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                        "",0L,
                                        "商品链接解析失败")));
                                return false;
                            }

                            ConvertGoodsDto data = analyzeRes.getData();
                            if (Objects.isNull(data)) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                        "",0L,
                                        "商品链接解析失败")));
                                return false;
                            }

                            List<Integer> supportPlatform = Lists.newArrayList(PlatformTypeEnum.PT_TAOBAO_VALUE, PlatformTypeEnum.PT_JD_VALUE, PlatformTypeEnum.PT_VPH_VALUE, PlatformTypeEnum.PT_PDD_VALUE);
                            if (!supportPlatform.contains(data.getPlatform().getId())) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                        "",0L,
                                        "平台目前只支持淘宝、京东、拼多多、唯品会商品链接解析")));
                                return false;
                            }

                            //通过商品链接进行转链
                            SimpleTurnlinkVo content_simpleTurnlinkVo = turnlinkSimple(null, null, shortUrl_old, device, null, pyqFollowConfig.getDevicePlanId(), data.getPlatform().getId());
                            if (content_simpleTurnlinkVo != null) {
                                if(StringUtils.isNotBlank(content_simpleTurnlinkVo.getItemId())){
                                    itemId = content_simpleTurnlinkVo.getItemId();
                                    itemName = content_simpleTurnlinkVo.getItemName();
                                }

                                //淘口令
                                pyqJobDetail.setItemPwd(content_simpleTurnlinkVo.getBuyPwd());
                                //设置打开淘宝url
                                pyqJobDetail.setPwdShortUrl(content_simpleTurnlinkVo.getPwdShortUrl());
                                //新的短链接
                                String content_buyUrl_new = Tools.getStr(content_simpleTurnlinkVo.getBuyUrl());
                                if (StringUtils.isBlank(content_buyUrl_new)) {
                                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                            pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                            "",0L,
                                            "购买链接转链为空")));
                                    return false;
                                }
                                content = content.replace(shortUrl_old, content_buyUrl_new);
                            }
                        }
                    }
                }

                //淘口令替换
                List<String> content_purePwdList_old  = Tools.findTbPwdListByRegex(content);
                if(content_purePwdList_old != null && content_purePwdList_old.size() > 0){
                    for (String content_purePwd_old : content_purePwdList_old){
                        if(StringUtils.isNotBlank(content_purePwd_old)){
                            SimpleTurnlinkVo content_simpleTurnlinkVo = turnlinkSimple(null, content_purePwd_old, null, device, null, pyqFollowConfig.getDevicePlanId(), PlatformTypeEnum.PT_TAOBAO_VALUE);
                            if(content_simpleTurnlinkVo != null){

                                if(StringUtils.isNotBlank(content_simpleTurnlinkVo.getItemId())){
                                    itemId = content_simpleTurnlinkVo.getItemId();
                                    itemName = content_simpleTurnlinkVo.getItemName();
                                }

                                //新的淘口令
                                String content_purePwd_new = Tools.getStr(content_simpleTurnlinkVo.getBuyPwd());
                                if(StringUtils.isBlank(content_purePwd_new)){//如果新淘口令为空，则不发送
                                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                            pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                            "",0L,
                                            "淘口令为空")));
                                    return false;
                                }

                                //淘口令
                                pyqJobDetail.setItemPwd(content_purePwd_new);
                                //设置打开淘宝url
                                pyqJobDetail.setPwdShortUrl(content_simpleTurnlinkVo.getPwdShortUrl());

                                content = content.replace(content_purePwd_old, content_purePwd_new);
                            }
                        }
                    }
                }
            }
        }
        pyqJobDetail.setContent(content);

        //关键词过滤
        String ignore = pyqFollowConfig.getIgnore();
        if(StringUtils.isNotBlank(ignore)){
            try {
                List<String> ignoreList = JSONObject.parseArray(ignore, String.class);
                if(ignoreList != null && ignoreList.size() > 0){
                    for (String ignoreKey : ignoreList){
                        if(content.contains(ignoreKey)){
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                    pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                    "",0L,
                                    "关键词过滤，内容为：" +content+"；关键词："+ignoreKey)));
                            return false;
                        }
                    }
                }
            }catch (Exception e){

            }
        }

        //是否开启插入随机表情
        Integer emoji = Tools.getInteger(pyqFollowConfig.getEmoji());
        if(emoji == 1){ //开启插入随机表情
            //朋友圈内容结尾插2个
            //content = EmojiUtil.getRandomEmoji() + EmojiUtil.getRandomEmoji() + content + EmojiUtil.getRandomEmoji() + EmojiUtil.getRandomEmoji();
            content = content + EmojiUtil.getRandomEmoji() + EmojiUtil.getRandomEmoji();
            pyqJobDetail.setContent(content);
        }


        //修改跟发朋友圈记录的商品信息
        try {
            if(StringUtils.isNotBlank(itemId)){
                PyqFollowedContent pyqFollowedContent = new PyqFollowedContent();
                pyqFollowedContent.setSnsId(pyqInfoDto.getSnsId());
                pyqFollowedContent.setItemId(itemId);
                pyqFollowedContent.setItemName(itemName);
                pyqFollowedContentMapper.updateItemInfoBySnsId(pyqFollowedContent);
            }
        }catch (Exception e){
            logger.error("修改跟发朋友圈记录的商品信息，出错，eror={}",e.getMessage());
        }

        List<PyqJobDetail> pyqJobDetailList = new ArrayList<>();
        pyqJobDetailList.add(pyqJobDetail);

        try{

            // UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.pyqMsgPush(pyqJobDetailList);
            //elasticsearchUtil.addData(JSONObject.parseObject(JSONObject.toJSONString(pyqJobDetail)), EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetail.getId());
            String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetail.getMerId());
            //保存发送消息
            List<Map<String, Object>> list = BeanMapUtil.objectList2ListMap(pyqJobDetailList);
            boolean result = elasticsearchUtilGroupMsg.addDataBatch(list, uzai_pyq_job_detail);

            logger.info("跟发朋友圈功能-发送内容，调用微服务发送明细完成---机器人唯一id={}, result={}", pyqJobDetail.getDeviceUniqueId(), JSONObject.toJSONString(result));
            if(result){ //成功发送
                //插入自动发送记录表中
                PyqFollowContent pyqFollowContent = new PyqFollowContent();
                pyqFollowContent.setId(IdWorker.getId());
                pyqFollowContent.setMerId(pyqFollowConfig.getMerId());
                pyqFollowContent.setDeviceUniqueId(deviceUniqueId);
                pyqFollowContent.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                pyqFollowContent.setPyqId(pyqJobDetail.getId());
                pyqFollowContent.setFollowedSnsId(pyqInfoDto.getSnsId());
                pyqFollowContent.setReleaseWxid(device.getDeviceId());
                pyqFollowContent.setReleaseNickname(device.getDeviceName());
                pyqFollowContent.setReleaseTime(now);
                pyqFollowContent.setSendTime(now);
                pyqFollowContent.setContent(pyqJobDetail.getContent());
                pyqFollowContent.setImg(pyqJobDetail.getImgs());
                pyqFollowContent.setAttachType(pyqInfoDto.getAttachType());
                pyqFollowContent.setFeedMedia(Tools.getStrEmpty(JSONObject.toJSONString(pyqInfoDto.getMediaList())));
                pyqFollowContent.setVideoNumber(Tools.getStrNull(JSONObject.toJSONString(pyqInfoDto.getPyqVideoNumberDto())));
                pyqFollowContent.setCreateTime(now);
                pyqFollowContent.setUpdateTime(now);
                //添加到记录表中
                pyqFollowContentMapper.insertSelective(pyqFollowContent);
            }
        }catch (Exception e){
            logger.error("跟发朋友圈发送内容，出错，eror={}",e.getMessage());
            return false;
        }

        return true;
    }

    /**
     * 跟发发送朋友圈评论
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param pyqFollowConfig
     * @return null
     */
    public boolean sendCommentPyqJobDetail(PyqFollowConfig pyqFollowConfig, Long deviceUniqueId, Long pyqJobId , PyqComment pyqComment, Integer now){

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, null, pyqFollowConfig.getMerId());
        if(device == null){
            return false;
        }

        //查询朋友圈主键id
        PyqFollowComment pyqFollowComment = new PyqFollowComment();
        pyqFollowComment.setId(IdWorker.getId());
        pyqFollowComment.setMerId(pyqFollowConfig.getMerId());
        pyqFollowComment.setDeviceUniqueId(deviceUniqueId);
        pyqFollowComment.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
        pyqFollowComment.setPyqId(null);
        pyqFollowComment.setFollowedSnsId(pyqComment.getSnsId());
        pyqFollowComment.setFollowedCommentId(pyqComment.getCommentId());
        pyqFollowComment.setCommentWxid(pyqComment.getCommentWxid());
        pyqFollowComment.setCommentNick(pyqComment.getCommentNick());
        pyqFollowComment.setContent(Tools.getStr(pyqComment.getContent()));
        pyqFollowComment.setCommentTime(pyqComment.getCommentTime());
        pyqFollowComment.setStatus(0); //未发送
        pyqFollowComment.setCreateTime(now);
        pyqFollowComment.setUpdateTime(now);

        String commentContent = Tools.getStr(pyqComment.getContent());

        //商品信息
        String itemId = null;
        String itemName = null;

        if(Tools.getInteger(pyqFollowConfig.getTurnlink()).intValue() == 1) { //--开启替换
            if(StringUtils.isNotBlank(commentContent)){
                //替换短链接
                //先解析第三方工具商的短链接
                List<String> shortUrlList_old = Tools.findHttpUrlListByRegex(commentContent);
                if(shortUrlList_old != null && shortUrlList_old.size() > 0){
                    for (String shortUrl_old : shortUrlList_old){
                        if(StringUtils.isNotBlank(shortUrl_old)){//不等于空，则调用解析第三方工具商短链接接口

                            TextConvertGoodsDto textConvertGoodsDto = new TextConvertGoodsDto();
                            textConvertGoodsDto.setMerId(pyqFollowConfig.getMerId());
                            textConvertGoodsDto.setText(shortUrl_old);
                            UzaiRespVo<ConvertGoodsDto> analyzeRes = clientApiService.convertGoods(textConvertGoodsDto);
                            if (analyzeRes.getCode() != 200) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                        "",0L,
                                        "商品链接解析失败")));
                                return false;
                            }

                            ConvertGoodsDto data = analyzeRes.getData();
                            if (Objects.isNull(data)) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                        "",0L,
                                        "商品链接解析失败")));
                                return false;
                            }

                            List<Integer> supportPlatform = Lists.newArrayList(PlatformTypeEnum.PT_TAOBAO_VALUE, PlatformTypeEnum.PT_JD_VALUE, PlatformTypeEnum.PT_VPH_VALUE, PlatformTypeEnum.PT_PDD_VALUE);
                            if (!supportPlatform.contains(data.getPlatform().getId())) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                        "",0L,
                                        "平台目前只支持淘宝、京东、拼多多、唯品会商品链接解析")));
                                return false;
                            }

                            //通过商品id进行转链
                            SimpleTurnlinkVo commentContent_simpleTurnlinkVo = turnlinkSimple(null, null, shortUrl_old, device, null, pyqFollowConfig.getDevicePlanId(), data.getPlatform().getId());
                            if(commentContent_simpleTurnlinkVo != null){

                                if(StringUtils.isNotBlank(commentContent_simpleTurnlinkVo.getItemId())){
                                    itemId = commentContent_simpleTurnlinkVo.getItemId();
                                    itemName = commentContent_simpleTurnlinkVo.getItemName();
                                }

                                //新的短链接
                                String commentContent_buyUrl_new = Tools.getStr(commentContent_simpleTurnlinkVo.getBuyUrl());
                                //如果短链接为空，不发送
                                if(StringUtils.isBlank(commentContent_buyUrl_new)){
                                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                            pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                            "",0L,
                                            "购买链接转链为空")));
                                    return false;
                                }
                                commentContent = commentContent.replace(shortUrl_old, commentContent_buyUrl_new);
                            }
                        }
                    }
                }

                //替换淘口令
                List<String> commentContent_purePwdList_old  = Tools.findTbPwdListByRegex(commentContent);
                if(commentContent_purePwdList_old != null && commentContent_purePwdList_old.size() > 0){
                    for (String commentContent_purePwd_old : commentContent_purePwdList_old){
                        if(StringUtils.isNotBlank(commentContent_purePwd_old)){
                            SimpleTurnlinkVo commentContent_simpleTurnlinkVo = turnlinkSimple(null, commentContent_purePwd_old,null, device, null, pyqFollowConfig.getDevicePlanId(), PlatformTypeEnum.PT_TAOBAO_VALUE);
                            if(commentContent_simpleTurnlinkVo != null){

                                if(StringUtils.isNotBlank(commentContent_simpleTurnlinkVo.getItemId())){
                                    itemId = commentContent_simpleTurnlinkVo.getItemId();
                                    itemName = commentContent_simpleTurnlinkVo.getItemName();
                                }

                                //新的淘口令
                                String commentContent_purePwd_new = Tools.getStr(commentContent_simpleTurnlinkVo.getPurePwd());
                                if(StringUtils.isBlank(commentContent_purePwd_new)){
                                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                            pyqFollowConfig.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                            "",0L,
                                            "未获取到淘口令")));
                                    return false;
                                }
                                commentContent = commentContent.replace(commentContent_purePwd_old, commentContent_purePwd_new);
                            }
                        }
                    }
                }
            }
            pyqFollowComment.setContent(commentContent);
        }

        //关键词过滤
        String ignore = pyqFollowConfig.getIgnore();
        if(StringUtils.isNotBlank(ignore)){
            try {
                List<String> ignoreList = JSONObject.parseArray(ignore, String.class);
                if(ignoreList != null && ignoreList.size() > 0){
                    for (String ignoreKey : ignoreList){
                        if(commentContent.contains(ignoreKey)){
                            return false;
                        }
                    }
                }
            }catch (Exception e){

            }
        }

        //是否开启插入随机表情
//        Integer emoji = Tools.getInteger(pyqFollowConfig.getEmoji());
//        if(emoji == 1){ //开启插入随机表情
//            //朋友圈评论结尾插一个
//            //commentContent = EmojiUtil.getRandomEmoji() + commentContent + EmojiUtil.getRandomEmoji();
//            commentContent = commentContent + EmojiUtil.getRandomEmoji();
//            pyqFollowComment.setContent(commentContent);
//        }
        pyqFollowCommentMapper.insertSelective(pyqFollowComment);


        //修改跟发朋友圈记录的商品信息
        try {
            if(StringUtils.isNotBlank(itemId)){
                PyqFollowedContent pyqFollowedContent = new PyqFollowedContent();
                pyqFollowedContent.setSnsId(pyqComment.getSnsId());
                pyqFollowedContent.setItemId(itemId);
                pyqFollowedContent.setItemName(itemName);
                pyqFollowedContentMapper.updateItemInfoBySnsId(pyqFollowedContent);
            }
        }catch (Exception e){
            logger.error("修改跟发朋友圈记录的商品信息，出错，eror={}",e.getMessage());
        }

        return true;
    }


    /**
     * 删除24小时之前的跟发记录
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param beforeDay
     */
    public void deleteBeforeDay(Integer beforeDay) {
        //删除被跟发朋友圈内容记录
        pyqFollowedContentMapper.deleteBeforeDay(beforeDay);
        //删除跟发朋友圈内容记录
        pyqFollowContentMapper.deleteBeforeDay(beforeDay);
        //删除跟发朋友圈评论记录
        pyqFollowedCommentMapper.deleteBeforeDay(beforeDay);
        //删除跟发朋友圈评论记录
        pyqFollowCommentMapper.deleteBeforeDay(beforeDay);
        //删除自动发送发送朋友圈(7天)
        int deleteDay = DateUtil.getNowTime() - 7*24*3600;
        //朋友圈自动发送历史记录
        pyqAutoSendMapper.deleteBeforeDay(deleteDay);
    }

    /**
     * 解析淘口令，获取商品id
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param  content
     * @param  deviceWechatInfo
     */
    private TbPwdAnalysisVo tbPwdAnalysis(String content, DeviceWechatInfo deviceWechatInfo){
        TbPwdAnalysisVo tbPwdAnalysisVo = new TbPwdAnalysisVo();

        if(StringUtils.isBlank(content)){
            return tbPwdAnalysisVo;
        }

        if(deviceWechatInfo == null){
            return tbPwdAnalysisVo;
        }

        //调用获取淘口令微服务接口
        TbPwdAnalysisDto tbPwdAnalysisDto = new TbPwdAnalysisDto();
        tbPwdAnalysisDto.setMerId(deviceWechatInfo.getMerId());
        tbPwdAnalysisDto.setDeviceId(deviceWechatInfo.getDeviceId());
        tbPwdAnalysisDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        tbPwdAnalysisDto.setDeviceUniqueId(deviceWechatInfo.getId());
        tbPwdAnalysisDto.setPwd(content);
        tbPwdAnalysisDto.setReqId(String.valueOf(IdWorker.getId()));
        UzaiRespVo<TbPwdAnalysisVo> uzaiRespVo = uzaiTurnlinkFeignService.tbPwdAnalysis(tbPwdAnalysisDto);
        logger.info("--调用解析淘口令微服务接口--,para={}, result={}", JSONObject.toJSONString(tbPwdAnalysisDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            return uzaiRespVo.getData();
        }
        return tbPwdAnalysisVo;
    }

    /**
     * 解析第三方工具商的短链接
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param  url
     * @param  device
     */
    private TbPartnerurlAnalysisVo tbPartnerurlAnalysis(String url, Device device){
        TbPartnerurlAnalysisVo tbPartnerurlAnalysisVo = new TbPartnerurlAnalysisVo();

        if(StringUtils.isBlank(url)){
            return tbPartnerurlAnalysisVo;
        }

        if(device == null){
            return tbPartnerurlAnalysisVo;
        }

        //调用获取淘口令微服务接口
        TbPartnerurlAnalysisDto tbPartnerurlAnalysisDto = new TbPartnerurlAnalysisDto();
        tbPartnerurlAnalysisDto.setMerId(device.getMerId());
        tbPartnerurlAnalysisDto.setDeviceId(device.getDeviceId());
        tbPartnerurlAnalysisDto.setDeviceType(device.getRecvmsgType());
        tbPartnerurlAnalysisDto.setDeviceUniqueId(device.getId());
        tbPartnerurlAnalysisDto.setUrl(url);
        tbPartnerurlAnalysisDto.setReqId(String.valueOf(IdWorker.getId()));
        UzaiRespVo<TbPartnerurlAnalysisVo> uzaiRespVo = uzaiTurnlinkFeignService.tbPartnerurlAnalysis(tbPartnerurlAnalysisDto);
        logger.info("--调用解析第三方工具商的短链接微服务接口--,para={}, result={}", JSONObject.toJSONString(tbPartnerurlAnalysisDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            return uzaiRespVo.getData();
        }
        return tbPartnerurlAnalysisVo;
    }

    /**
     * 转链生成新的淘口令
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param  pwd
     * @para bizSceneId:务场景ID 非必填，解析淘口令得接口返回了就带过来，没返回就不带
     * @param  device
     */
    private SimpleTurnlinkVo turnlinkSimple(String itemId, String pwd, String url, Device device, String bizSceneId, Long devicePlanId, Integer platform){

        SimpleTurnlinkVo simpleTurnlinkVo = new SimpleTurnlinkVo();

        if(StringUtils.isBlank(pwd) && StringUtils.isBlank(itemId) && StringUtils.isBlank(url)){
            return simpleTurnlinkVo;
        }

        if(device == null){
            return simpleTurnlinkVo;
        }

        if(devicePlanId == null){
            logger.error("请选择设备方案");
            return simpleTurnlinkVo;
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(devicePlanId, device.getMerId());

        if(pyqDevicePlan == null){
            logger.info("该设备方案不存在");
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该设备方案不存在");
        }

        Long tbTokenId = null;
        String pid = "";
        Long jdTokenId = null;
        Long pddTokenId = null;
        Long vphTokenId = null;
        Long dyTokenId = null;
        Integer pddTokenType = null;
        Integer dyTokenType = null;
        Integer jdTokenType = null;
        Integer vphTokenType = null;

        if(pyqDevicePlan.getTokenType() != null && pyqDevicePlan.getTokenType().intValue() == 1){ //自己设置联盟
            JSONObject jsonObjectToken = JSONObject.parseObject(pyqDevicePlan.getTokenInfo());
            if(jsonObjectToken != null){
                //淘宝token
                JSONObject tbTokenJsonObject  = jsonObjectToken.getJSONObject("tbToken");
                if(tbTokenJsonObject != null){
                    tbTokenId = tbTokenJsonObject.getLong("tokenId");
                    pid = tbTokenJsonObject.getString("pid");
                }
                //京东token
                JSONObject jdTokenJsonObject  = jsonObjectToken.getJSONObject("jdToken");
                if(jdTokenJsonObject != null){
                    jdTokenId = jdTokenJsonObject.getLong("tokenId");
                    jdTokenType = jdTokenJsonObject.getInteger("type");
                }
                //拼多多token
                JSONObject pddTokenJsonObject  = jsonObjectToken.getJSONObject("pddToken");
                if(pddTokenJsonObject != null){
                    pddTokenId = pddTokenJsonObject.getLong("tokenId");
                    pddTokenType = pddTokenJsonObject.getInteger("type");
                }
                //唯品会token
                JSONObject vphTokenJsonObject  = jsonObjectToken.getJSONObject("vphToken");
                if(vphTokenJsonObject != null){
                    vphTokenId = vphTokenJsonObject.getLong("tokenId");
                    vphTokenType = vphTokenJsonObject.getInteger("type");
                }
                //抖音token
                JSONObject dyTokenJsonObject  = jsonObjectToken.getJSONObject("dyToken");
                if(dyTokenJsonObject != null){
                    dyTokenId = dyTokenJsonObject.getLong("tokenId");
                    dyTokenType = dyTokenJsonObject.getInteger("type");
                }
            }
        }else{ //默认从机器人中获取
            ConfigPlan configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
            if(configPlan != null){
                //淘宝商品转链不去配置方案中查找，因为淘宝商品要拿导购联盟转链
                if(false){
                    JSONObject jsonObject_tb = JSONObject.parseObject(configPlan.getTbAccountId());
                    if(jsonObject_tb != null) {
                        JSONArray jsonArray = jsonObject_tb.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                tbTokenId = tokenList.get(0);
                                TbToken tbToken = tbTokenMapper.selectById(tbTokenId, device.getMerId());
                                if (tbToken != null) {
                                    pid = tbToken.getDefPid();
                                }
                            }
                        }
                    }
                }

                //京东token
                JSONObject jsonObject_jd = null;
                jdTokenType = configPlan.getJdAccountType();
                if(jdTokenType != null && jdTokenType.intValue() == 1){ //推老板共享联盟
                    jsonObject_jd = JSONObject.parseObject(configPlan.getTlbJdAccountId());
                }else{ //拼多多联盟
                    jsonObject_jd = JSONObject.parseObject(configPlan.getJdAccountId());
                }
                if(jsonObject_jd != null) {
                    JSONArray jsonArray = jsonObject_jd.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            jdTokenId = tokenList.get(0);
                        }
                    }
                }

                //唯品会token
                JSONObject jsonObject_vph = null;
                vphTokenType = configPlan.getVphAccountType();
                if(vphTokenType != null && vphTokenType.intValue() == 1){ //推老板共享联盟
                    jsonObject_vph = JSONObject.parseObject(configPlan.getTlbVphAccountId());
                }else{ //拼多多联盟
                    jsonObject_vph = JSONObject.parseObject(configPlan.getVphAccountId());
                }
                if(jsonObject_vph != null) {
                    JSONArray jsonArray = jsonObject_vph.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            vphTokenId = tokenList.get(0);
                        }
                    }
                }

                //拼多多token
                JSONObject jsonObject_pdd = null;
                pddTokenType = configPlan.getPddAccountType();
                if(configPlan.getPddAccountType() != null && configPlan.getPddAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_pdd = JSONObject.parseObject(configPlan.getTlbPddAccountId());
                }else{ //拼多多联盟
                    jsonObject_pdd = JSONObject.parseObject(configPlan.getPddAccountId());
                }
                if(jsonObject_pdd != null) {
                    JSONArray jsonArray = jsonObject_pdd.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            pddTokenId = tokenList.get(0);
                        }
                    }
                }

                //dytoken
                JSONObject jsonObject_dy = null;
                dyTokenType = configPlan.getDyAccountType();
                if(configPlan.getDyAccountType() != null && configPlan.getDyAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_dy = JSONObject.parseObject(configPlan.getTlbDyAccountId());
                }else{ //拼多多联盟
                    jsonObject_dy = JSONObject.parseObject(configPlan.getDyAccountId());
                }
                if(jsonObject_dy != null) {
                    JSONArray jsonArray = jsonObject_dy.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            dyTokenId = tokenList.get(0);
                        }
                    }
                }
            }
        }

        //调用获取转链微服务接口
        SimpleTurnLinkDto simpleTurnLinkDto = new SimpleTurnLinkDto();
        simpleTurnLinkDto.setMerId(device.getMerId());
        simpleTurnLinkDto.setDeviceType(device.getRecvmsgType());
        simpleTurnLinkDto.setDeviceUniqueId(device.getId());
        simpleTurnLinkDto.setItemId(itemId);
        simpleTurnLinkDto.setPwd(pwd);
        simpleTurnLinkDto.setUrl(url);
        simpleTurnLinkDto.setBizSceneId(bizSceneId);
        simpleTurnLinkDto.setGenerateShortUrl(1);
        simpleTurnLinkDto.setMiddlePageDomainId(pyqDevicePlan.getDomain());
        simpleTurnLinkDto.setChannel(OrderSourceEnum.WECHAT_PYQ.getId());//微信朋友圈

        platform = Tools.getInteger(platform);

        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = null;
        if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == platform.intValue()){ //淘宝
            if(tbTokenId == null) { //设备方案未配置淘宝联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "朋友圈-设备方案未配置淘宝联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置淘宝联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

            }else{
                simpleTurnLinkDto.setTokenId(tbTokenId);
                simpleTurnLinkDto.setPid(pid);
                uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用淘宝转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }else if(PlatformTypeEnum.PT_JD.getId().intValue() == platform.intValue()){ //京东

            if(jdTokenId == null){ //发单设备方案未配置京东联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置京东联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置京东联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

            }else{
                simpleTurnLinkDto.setTokenId(jdTokenId);
                simpleTurnLinkDto.setJdTokenType(jdTokenType);
                uzaiRespVo = uzaiTurnlinkFeignService.jdTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用京东转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }else if(PlatformTypeEnum.PT_PDD.getId().intValue() == platform.intValue()){ //拼多多
            if(pddTokenId == null){ //发单设备方案未配置拼多多联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置拼多多联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置拼多多联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
            }else{
                simpleTurnLinkDto.setTokenId(pddTokenId);
                simpleTurnLinkDto.setPddTokenType(pddTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.pddTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用拼多多转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(PlatformTypeEnum.PT_VPH.getId().intValue() == platform.intValue()){ //唯品会
            if(vphTokenId == null){ //发单设备方案未配置唯品会联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置唯品会联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置唯品会联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
            }else{
                simpleTurnLinkDto.setTokenId(vphTokenId);
                simpleTurnLinkDto.setVphTokenType(vphTokenType);
                uzaiRespVo =uzaiTurnlinkFeignService.vphTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用唯品会转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }

        logger.info("--朋友圈自动跟发调用淘宝转链微服务接口--,para={}, result={}", JSONObject.toJSONString(simpleTurnLinkDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            simpleTurnlinkVo =  uzaiRespVo.getData();
        }else{
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                    device.getMerId(), device.getRecvmsgType(), device.getId(),
                    "",0L,
                    "----转链失败----")));
        }

        return simpleTurnlinkVo;
    }

}
